package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogBuyBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.ReportFreeGiftCodeStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.recycler.RecyclerDialogBuyListAdpter;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.HashMap;
import java.util.Map;

public class BuyDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        SET_PRICE(3),
        RESET_COUNTDOWM(4),
        RESET_COUNTDOWM_TOAST(5),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<? extends DialogAbstract> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getContext(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                if (MyApp.getInstance().getBuyList().size() <= 0) {
                    dialogCancel();
                } else {
                    Option option = optionMap.get(commandCode);

                    switch (option) {
                        case TOAST:
                                super.execute(context, commandCode, message);
                            break;
                        case COUNTDOWN_CANCEL:
                                cancelOnThreadCountdown();
                            break;
                        case SET_COUNTDOWN_TEXT:
                                setButtonCancelText(Integer.valueOf(message));
                            break;
                        case SET_PRICE:
                            String status = "";
                            if (!MyApp.getInstance().getReportFreeGiftCodeStructure().getFreeGiftId().isEmpty()) {
                                switch (MyApp.getInstance().getReportFreeGiftCodeStructure().getMode()) {
                                    case 0:
                                        break;
                                    case 1:
                                        status = "("+context.getString(R.string.discounted)+MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountAmount()+")";
                                        break;
                                    case 2:
                                        status = "("+context.getString(R.string.discounted1)+MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountPercentage()+")";
                                        break;
                                }
                            }

                                binding.textPrice.setText(getTotalPrice()+status);
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM:
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM_TOAST:
                                super.execute(context, commandCode, message);
                                closeDialogCountdown.setCountdown(40);
                            break;
                    }
                }
            }
        };
    }

    private DialogBuyBinding binding;
    private RecyclerDialogBuyListAdpter recyclerDialogBuyListAdpter;
    private CloseDialogOnThreadHandler closeDialogCountdown;

    public BuyDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
        getLogs().info("open:" + getClass().getSimpleName());
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogBuyBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        // 讀取最後設定語言的設定
        LanguageHelper.applySavedLanguage(context);

        this.recyclerDialogBuyListAdpter = new RecyclerDialogBuyListAdpter(getCtx(), MyApp.getInstance().getBuyList(), getHandlerMain());
        this.binding.recyclerDialogBuyList.setAdapter(recyclerDialogBuyListAdpter);
        this.binding.recyclerDialogBuyList.setLayoutManager(new LinearLayoutManager(context));

        MyApp.getInstance().initialReportData();
        MyApp.getInstance().getReportFlowInfoData().setOrderId(Tools.generateTimeBasedUUID());
        MyApp.getInstance().getPostInvoiceByGreenData().setOrderId(MyApp.getInstance().getReportFlowInfoData().getOrderId());

        this.binding.layoutPaymentTransactions.setVisibility(View.VISIBLE);
        this.binding.layoutVerificationPickup.setVisibility(View.GONE);
        this.binding.layoutMemberTransactions.setVisibility(View.GONE);

        this.binding.buttonPaymentTransactions.setOnClickListener(view -> {
            this.binding.layoutPaymentTransactions.setVisibility(View.VISIBLE);
            this.binding.layoutVerificationPickup.setVisibility(View.GONE);
            this.binding.layoutMemberTransactions.setVisibility(View.GONE);
            closeDialogCountdown.setCountdown(40);
        });

        this.binding.buttonVerificationPickup.setOnClickListener(view -> {
            this.binding.layoutPaymentTransactions.setVisibility(View.GONE);
            this.binding.layoutVerificationPickup.setVisibility(View.VISIBLE);
            this.binding.layoutMemberTransactions.setVisibility(View.GONE);
            closeDialogCountdown.setCountdown(40);
        });

        this.binding.buttonMemberTransactions.setOnClickListener(view -> {

        });



        this.binding.buttonCash.setOnClickListener(v -> {
            MyApp.getInstance().getReportFlowInfoData().setFlowType(9);
            gotoDialog();
        });

        this.binding.buttonAccessCode.setOnClickListener(v -> {
            MyApp.getInstance().getReportFlowInfoData().setFlowType(5);
            gotoDialog();
        });

        this.binding.buttonFreeGift.setOnClickListener(v -> {
            MyApp.getInstance().getReportFlowInfoData().setFlowType(7);
            gotoDialog();
        });

        this.binding.buttonAddProduct.setOnClickListener(v -> gotoAddProduct());
        this.binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

        String status = "";
        if (!MyApp.getInstance().getReportFreeGiftCodeStructure().getFreeGiftId().isEmpty()) {
            switch (MyApp.getInstance().getReportFreeGiftCodeStructure().getMode()) {
                case 0:
                    break;
                case 1:
                    status = "("+context.getString(R.string.discounted)+MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountAmount()+")";
                    break;
                case 2:
                    status = "("+context.getString(R.string.discounted1)+MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountPercentage()+")";
                    break;
            }
        }
        binding.textPrice.setText(getTotalPrice()+status);

        if (MyApp.getInstance().getDevSet().isShoppingCar()) {
            binding.buttonAddProduct.setVisibility(View.VISIBLE);
        } else {
            binding.buttonAddProduct.setVisibility(View.GONE);
        }

        if (MyApp.getInstance().getDevSet().isShoppingCar()) {
            if (MyApp.getInstance().getDevSet().isDevCash()) {
                binding.buttonCash.setVisibility(View.VISIBLE);
                binding.placeholderView13.setVisibility(View.GONE);
            } else {
                binding.buttonCash.setVisibility(View.GONE);
                binding.placeholderView13.setVisibility(View.GONE);
            }
        } else {
            BuyStructure buyData = MyApp.getInstance().getBuyList().get(0);

            try {
                SlotField slotField = SlotField.getSlotField(buyData.getField());



                if (MyApp.getInstance().getDevSet().isDevCash()) {
                    if (slotField.isDevCash()) {
                        binding.buttonCash.setVisibility(View.VISIBLE);
                        binding.placeholderView13.setVisibility(View.GONE);
                    } else {
                        binding.buttonCash.setVisibility(View.GONE);
                        binding.placeholderView13.setVisibility(View.GONE);
                    }
                } else {
                    binding.buttonCash.setVisibility(View.GONE);
                    binding.placeholderView13.setVisibility(View.GONE);
                }
            } catch (LogsEmptyException e) {


                if (MyApp.getInstance().getDevSet().isDevCash()) {
                    binding.buttonCash.setVisibility(View.VISIBLE);
                    binding.placeholderView13.setVisibility(View.GONE);
                } else {
                    binding.buttonCash.setVisibility(View.GONE);
                    binding.placeholderView13.setVisibility(View.GONE);
                }
            }
        }
    }

    public int getTotalPrice() {
        int totalPrice = 0;
        if (MyApp.getInstance().getBuyList().isEmpty()) {
            return totalPrice;
        }
        for(BuyStructure buy: MyApp.getInstance().getBuyList()) {
            if (!buy.isFreeGift()) totalPrice += buy.getFullPrice();
        }
        if (!MyApp.getInstance().getReportFreeGiftCodeStructure().getFreeGiftId().isEmpty()) {
            switch (MyApp.getInstance().getReportFreeGiftCodeStructure().getMode()) {
                case 0:
                    break;
                case 1:
                    totalPrice = totalPrice - MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountAmount();
                    break;
                case 2:
                    totalPrice = (int) (totalPrice * MyApp.getInstance().getReportFreeGiftCodeStructure().getDiscountPercentage());
                    break;
            }
        }
        if (totalPrice == 0) totalPrice = 1;
        return totalPrice;
    }

    public void gotoAddProduct() {
        getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.ADD_PRODUCT.getOption(), "@請40秒內完成加購動作");
        closeDialogCountdown.shutdown();
        cancel();
    }

    public void dialogCancel() {
        MyApp.getInstance().setReportFreeGiftCodeStructure(new ReportFreeGiftCodeStructure("", 0, "", 0, 0, ""));
        getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "");
        closeDialogCountdown.shutdown();
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogBuyListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        cancel();
    }

    public void cancelOnThreadCountdown() {
        MyApp.getInstance().setReportFreeGiftCodeStructure(new ReportFreeGiftCodeStructure("", 0, "", 0, 0, ""));
        getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "");
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogBuyListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        getTools().dialogClose();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getContext().getString(R.string.cancel)+"("+countdown+")");//取消
    }

    public void gotoDialog() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        getLogs().info("aaaaaaaaaaaaaaaaaaaaaaaa"+flowType);
        if (flowType == 5 || flowType == 7) {
            changeCheckout();
        } else {
            if (MyApp.getInstance().getDevSet().isShoppingCar()) {
                if (MyApp.getInstance().getDevSet().isInvoice()) {
                    changeDialog(InvoiceBarcodeDialog.class);
                } else {
                    changeCheckout();
                }
            } else {
                if (MyApp.getInstance().getDevSet().isInvoice()) {
                    BuyStructure buyData = MyApp.getInstance().getBuyList().get(0);
                    try {
                        SlotField slotField = SlotField.getSlotField(buyData.getField());
                        if (slotField.isInvoice()) {
                            changeDialog(InvoiceBarcodeDialog.class);
                        } else {
                            changeCheckout();
                        }
                    } catch (LogsEmptyException e) {
                        changeDialog(InvoiceBarcodeDialog.class);
                    }
                } else {
                    changeCheckout();
                }
            }
        }
    }

    public void changeCheckout() {
        closeDialogCountdown.shutdown();
        int flowType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        switch (flowType) {
            case 5:
                changeDialog(CheckoutAccessCodeDialog.class);
                break;
            case 7:
                changeDialog(CheckoutFreeGiftCodeDialog.class);
                break;
            case 9:
                changeDialog(CheckoutCashDialog.class);
                break;
        }
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }
}
